package com.sgb.kjwl.view.ui.activity.lease;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityZulinGaodeSearchBinding;
import com.sgb.kjwl.model.LocationAddressInfo;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.house.LeaseHallMapActivity;
import com.sgb.kjwl.view.ui.activity.house.LeaseUseMapActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.CargoPublishContractActivity;
import com.sgb.kjwl.view.ui.adapter.lease.GaodeSearchAdapter;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 租赁首页高德地图搜索
 */
public class ZulinGaodeSearchActivity extends AppActivity implements PoiSearch.OnPoiSearchListener, AMapLocationListener {

    private List<LocationAddressInfo> historys = new ArrayList<>();
    private ArrayList<LocationAddressInfo> list = new ArrayList<>();

    private ActivityZulinGaodeSearchBinding binding;
    private GaodeSearchAdapter adapter;

    private String keyWord = "";// 要输入的poi搜索关键字
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private String searchCity = "";//要搜索的城市

    //定位需要的声明
    private AMapLocationClient mLocationClient = null;//定位发起端
    private AMapLocationClientOption mLocationOption = null;//定位参数
    private boolean flag = false;


    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ZulinGaodeSearchActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, boolean flag, String work) {
        Intent intent = new Intent();
        intent.setClass(context, ZulinGaodeSearchActivity.class);
        intent.putExtra("flag", flag);
        intent.putExtra("work", work);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }


    @Override
    protected void initView() {
        requestPermission();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_zulin_gaode_search);
        flag = getIntent().getBooleanExtra("flag", false);
        keyWord = getIntent().getStringExtra("work");

        binding.itemSearchAddr.ivBack.setOnClickListener(this);
        binding.itemSearchAddr.tvCancel.setOnClickListener(this);
//        binding.itmeEmpty.tvToSelect.setOnClickListener(this);
        binding.itemSearchAddr.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.itemSearchAddr.etSearch.setText("");
                binding.itemSearchAddr.tvSearchDelete.setVisibility(View.GONE);
            }
        });
        adapter = new GaodeSearchAdapter(this, list);
        binding.rv.setAdapter(adapter);
        adapter.setCallback(bean -> {
            if (bean.getTip() != 2) {
                bean.setTip(1);
                if (!historys.contains(bean)) {
                    historys.add(bean);
                    if (historys.size() > 10) {//最多保存10条历史记录,超过10条,删除最早的记录
                        historys.remove(0);
                    }
                    String json = new Gson().toJson(historys);
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.ZULIN_MAP_ADDR_SEARCH_HISTORY, json);
                }
            }
//            if("图选".equals(bean.getTitle())){
//                //跳转到地图选点确认界面
//                Bundle bundle = new Bundle();
//                bundle.putString("title", bean.getTitle());
//                bundle.putString("text", bean.getText());
//                bundle.putDouble("lat", bean.getLat());
//                bundle.putDouble("lon", bean.getLon());
//                LeaseUseMapActivity.start(getActivity(), bundle);
//                finish();
//            }else{
            Bundle bundle = new Bundle();
            bundle.putString("title", bean.getTitle());
            bundle.putString("text", bean.getTitle());
            bundle.putDouble("lat", bean.getLat());
            bundle.putDouble("lon", bean.getLon());

            if (flag) {
                LeaseHallMapActivity.startForBundle(getActivity(), bundle);
                finish();
            } else {
                Intent intent = new Intent();
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }

//            }

        });

        initEdit();
        getHistoryList();
    }

    private void initEdit() {
        binding.itemSearchAddr.etSearch.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_ENTER) {
                keyWord = binding.itemSearchAddr.etSearch.getText().toString();
                if (TextUtils.isEmpty(keyWord)) {
                    MToast.showToast(ZulinGaodeSearchActivity.this, "请输入关键字");
                } else {
                    // doSearchQuery(keyWord);
                    KeyboardUtils.hideSoftInput(binding.itemSearchAddr.etSearch);
                }
                return true;
            }
            return false;
        });
        binding.itemSearchAddr.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                keyWord = binding.itemSearchAddr.etSearch.getText().toString();
                if (!TextUtils.isEmpty(keyWord)) {
                    doSearchQuery(keyWord);
                    binding.itemSearchAddr.tvSearchDelete.setVisibility(View.VISIBLE);
                } else {
                    binding.itemSearchAddr.tvSearchDelete.setVisibility(View.GONE);
                    getHistoryList();
                }
            }
        });
    }


    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置定位权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
            } else {
                initLoc();
            }
        } else {
            initLoc();
        }
    }

    private void getHistoryList() {
        //取出本地存的搜索记录
        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ZULIN_MAP_ADDR_SEARCH_HISTORY, "");
        Gson gson = new Gson();
        Type type = new TypeToken<List<LocationAddressInfo>>() {
        }.getType();
        list.clear();
        List<LocationAddressInfo> hs = gson.fromJson(historyWords, type);
//        list.add(new LocationAddressInfo("图选", "可以在地图上选择使用地点哦！", 0.0, 0.0, "", 2));
        if (hs != null) {
            Collections.reverse(hs);
            historys.addAll(hs);
            list.addAll(hs);
        }
        adapter.notifyDataSetChanged();
        binding.rv.setVisibility(View.VISIBLE);
        if (adapter.getItemCount() > 0) {
            binding.itmeEmpty.root.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initLoc();
                } else {
                    // MToast.showToast(ZulinGaodeSearchActivity.this, "请求权限失败");
                }
                return;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_cancel:
                finish();
//                binding.itemSearchAddr.editSearch.setText("");
//                list.clear();
//                list.add(new LocationAddressInfo("图选", "可以在地图上选择使用地点哦！", 0.0, 0.0, "", 2));
//                list.addAll(historys);
//                adapter.notifyDataSetChanged();
//                binding.rv.setVisibility(View.VISIBLE);
//                binding.itmeEmpty.root.setVisibility(View.GONE);
//                KeyboardUtils.hideSoftInput(binding.itemSearchAddr.editSearch);
                break;
//            case R.id.tv_to_select:
//                Bundle bundle = new Bundle();
//                bundle.putString("title", "图选");
//                bundle.putString("text", "可以在地图上选择使用地点哦");
//                bundle.putDouble("lat", 0.0);
//                bundle.putDouble("lon", 0.0);
//                LeaseUseMapActivity.start(getActivity(), bundle);
//                finish();
//                break;
        }
    }

    //定位
    private void initLoc() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String key) {
        currentPage = 0;
        //不输入城市名称有些地方搜索不到
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(key, "", searchCity);
        // 设置每页最多返回多少条poiitem
        query.setPageSize(15);
        // 设置查询页码
        query.setPageNum(currentPage);

        //构造 PoiSearch 对象，并设置监听
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        //调用 PoiSearch 的 searchPOIAsyn() 方法发送请求。
        poiSearch.searchPOIAsyn();
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        //rCode 为1000 时成功,其他为失败
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            // 解析result   获取搜索poi的结果
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(query)) {  // 是否是同一条
                    poiResult = result;
                    ArrayList<LocationAddressInfo> data = new ArrayList<LocationAddressInfo>();//自己创建的数据集合
                    // 取得第一页的poiitem数据，页数从数字0开始
                    //poiResult.getPois()可以获取到PoiItem列表
                    List<PoiItem> poiItems = poiResult.getPois();


                    //解析获取到的PoiItem列表
                    for (PoiItem item : poiItems) {
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        //返回POI的名称
                        String title = item.getTitle();
                        //返回POI的地址
                        String text = item.getSnippet();
                        data.add(new LocationAddressInfo(title, text, lon, lat, keyWord, 0));
                    }
                    list.clear();
                    list.addAll(data);
//                    list.add(new LocationAddressInfo("图选", "没有找到合适使用地点，可以在地图上选择哦！", 0, 0, "", 2));
                    adapter.notifyDataSetChanged();
                    if (list.size() > 1) {
                        binding.rv.setVisibility(View.VISIBLE);
                        binding.itmeEmpty.root.setVisibility(View.GONE);
                    } else {
                        binding.rv.setVisibility(View.GONE);
                        binding.itmeEmpty.root.setVisibility(View.VISIBLE);
                    }

                }
            } else {
                MToast.showToast(ZulinGaodeSearchActivity.this, "无搜索结果");
                binding.rv.setVisibility(View.GONE);
                binding.itmeEmpty.root.setVisibility(View.VISIBLE);
            }
        } else {
            MToast.showToast(ZulinGaodeSearchActivity.this, "错误码");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                searchCity = amapLocation.getProvince();//省信息
                // amapLocation.getCity();//城市信息
            }
        }
    }


}
